//
// Created by 11510 on 2024/6/22.
//
/*
 * 理解shared_ptr的循环引用问题（面试容易问到），掌握解决的方法，通过代码验证
 */

#include <iostream>
#include <string>
#include <memory>
#include <vector>

using namespace std;

class Child;

class Parent {
public:
    Parent() { cout << "Parent()" << endl; }

    ~Parent() { cout << "~Parent()" << endl; }

// 只需要Child类型的指针，不需要类的完整定义
    weak_ptr<Child> _spChild;
};

class Child {
public:
    Child() { cout << "child()" << endl; }

    ~Child() { cout << "~child()" << endl; }

    shared_ptr<Parent> _spParent;
};


void test1() {
    shared_ptr<Parent> parent(new Parent());
    shared_ptr<Child> child(new Child());
    cout << parent.use_count() << endl;
    cout << child.use_count() << endl;

    parent->_spChild = child;
    child->_spParent = parent;
    cout << parent.use_count() << endl;
    cout << child.use_count() << endl;
}

int main() {
    test1();
    return 0;
}